package com.zhxh.nzpos.query;

import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;

import com.zhxh.nzpos.R;
import com.zhxh.nzpos.dao.CategoryDao;
import com.zhxh.nzpos.dao.LocalInfoDao;
import com.zhxh.nzpos.dao.SelloutDao;
import com.zhxh.nzpos.model.Category;
import com.zhxh.nzpos.model.LocalInfo;
import com.zhxh.nzpos.model.Sellout;
import com.zhxh.nzpos.serialport.PrintSerialPort;
import com.zhxh.nzpos.utils.ViewUtil;
import com.zhxh.nzpos.view.CustomDatePicker;

/**
 * 统计查询--订购查询
 * 
 * @author wangzt
 * 
 */
public class SellOutQueryActivity extends PrintSerialPort {

	private ArrayList<Sellout> selloutItems;
	private SelloutQueryAdapter listAdapter;

	private Calendar fromCal = Calendar.getInstance();
	private Calendar toCal = Calendar.getInstance();

	EditText fromDate;
	EditText toDate;
	SimpleDateFormat simpleDateFormat;
	SimpleDateFormat simpleDateFormat2;
	SimpleDateFormat simpleDateFormat3;
	private String[] category_items;
	private long total;
	private int pageSize = 5;
	private int currentPage = 1;

	Spinner typeSpinner;
	EditText goodsCode;
	SelloutDao selloutDao;
	CategoryDao categoryDao;
	LocalInfoDao dao;
	SendingThread mSendingThread;
	List<Category> list;
	private String name;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_query_sellout);
		selloutDao = new SelloutDao(this);
		categoryDao = new CategoryDao(this);
		dao = new LocalInfoDao(this);
		initViews();
	}

	private void initViews() {

		List<LocalInfo> locals = dao.getAll();
		if (locals.size() > 0)
			name = locals.get(0).getName();

		ListView listView = (ListView) findViewById(R.id.buyin_query_listview);
		selloutItems = new ArrayList<Sellout>();

		goodsCode = (EditText) findViewById(R.id.buyin_goods_code_et);

		typeSpinner = (Spinner) findViewById(R.id.query_goods_type_spinner);

		list = categoryDao.getAll();

		fromDate = (EditText) findViewById(R.id.buyin_from_date);
		toDate = (EditText) findViewById(R.id.buyin_to_date);
		simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		fromDate.setText(simpleDateFormat.format(fromCal.getTime()));
		toDate.setText(simpleDateFormat.format(toCal.getTime()));

		final CustomDatePicker fromPicker = new CustomDatePicker(this,
				fromDate, fromCal);
		fromDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				fromPicker.updateDate();
				fromPicker.show();
			}
		});

		final CustomDatePicker toPicker = new CustomDatePicker(this, toDate,
				toCal);
		toDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				toPicker.updateDate();
				toPicker.show();
			}
		});

		listAdapter = new SelloutQueryAdapter(getLayoutInflater(), selloutItems);
		listView.setAdapter(listAdapter);

		ImageView cancelBtn = (ImageView) findViewById(R.id.buyin_print_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (selloutItems.size() < 1) {
					ViewUtil.makeToast(getApplicationContext(), "请选择打印内容");
					return;
				}
				print();
			}
		});
	}

	private void print() {
		System.out.println("print/...........................");
		ViewUtil.showProgressDialog(SellOutQueryActivity.this, "正在处理...");
		new Thread() {
			public void run() {
				System.out.println("printing2222/...........................");
				// if (!shouldPrint.isChecked()) {
				if (mSerialPort != null) {
					mSendingThread = new SendingThread();
					mSendingThread.start();
				} else {
					System.out
							.println("serial is null/...........................");
				}
			}

		}.start();
		ViewUtil.cancelProgressDialog();

	}

	protected void onPrint(OutputStream mOutputStream) throws IOException {

		// TODO 按照格式补全打印信息
		Map<String, ArrayList<Sellout>> map = new HashMap<String, ArrayList<Sellout>>();
		for (Sellout sellout : selloutItems) {
			ArrayList<Sellout> list = map.get(sellout.getOrderId());
			if (list == null) {
				list = new ArrayList<Sellout>();
				list.add(sellout);
				map.put(sellout.getOrderId(), list);
			} else {
				list.add(sellout);
			}
		}

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		mOutputStream.write("\r\n".getBytes());
		mOutputStream.write(("      大兴农资安全监管系统\r\n").getBytes("gbk"));
		mOutputStream.write(("       " + name + "\r\n").getBytes("gbk"));
		mOutputStream.write(("          销售流水打印\r\n").getBytes("gbk"));
		mOutputStream.write(("日期范围:" + fromDate.getText().toString() + "--"
				+ toDate.getText().toString() + "\r\n").getBytes("gbk"));
		mOutputStream.write("================================\r\n"
				.getBytes("gbk"));

		Iterator iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			Object key = iterator.next();
			System.out.println("map.get(key) is :" + map.get(key));
			mOutputStream.write(("流水号:"+key+"\r\n").getBytes("gbk"));
			mOutputStream.write("商品名称     数量  单价  金额\r\n".getBytes("gbk"));
			
			ArrayList<Sellout> sells =  map.get(key);
			String sellDate = null;
			int amount = 0;
			for (Sellout sellout :sells) {
				sellDate = sellout.getSellDate();
				amount += sellout.getCount();
				String name = sellout.getGoodsName().trim();
				mOutputStream.write((name + "\r\n").getBytes("gbk"));
				mOutputStream.write(("              " + sellout.getCount()
						+ "    " + sellout.getPrice() + "  "
						+ sellout.getTotal() + "\r\n").getBytes("gbk"));

			}
			if(sellDate != null) {
				mOutputStream.write(("销售时间:"+sellDate+"\r\n").getBytes("gbk"));
			}
		}
		

		mOutputStream.write(("===============================\r\n")
				.getBytes("gbk"));
		mOutputStream.write(("      打印日期:"
				+ simpleDateFormat.format(new Date()) + "   \r\n ")
				.getBytes("gbk"));
		mOutputStream.write("\r\n\r\n".getBytes());

	}

	private class SendingThread extends Thread {
		@Override
		public void run() {
			// while (!isInterrupted()) {
			try {
				if (mOutputStream != null) {
					onPrint(mOutputStream);
					return;
				} else {
					return;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			// }
		}
	}

	public void search(View view) {
		// finish();
		currentPage = 1;
		doSearch(view);
		doGetCount(view);

	}

	public void page_next(View view) {

		if (currentPage * pageSize <= total) {
			currentPage++;
			doSearch(view);
		}

	}

	public void page_previous(View view) {

		currentPage--;

		if (currentPage < 1) {
			currentPage = 1;
		}

		doSearch(view);

	}

	public void doSearch(View view) {

		String cateId = null;

		String identifier = goodsCode.getText().toString();
		Date btime;
		Date etime;
		try {
			btime = simpleDateFormat.parse(fromDate.getText().toString());
			etime = simpleDateFormat2.parse(toDate.getText().toString()
					+ " 23:59:59");

			ArrayList<Sellout> items = selloutDao.getScrollData(cateId,
					identifier, btime.getTime(), etime.getTime(), currentPage,
					pageSize);
			selloutItems.clear();
			selloutItems.addAll(items);
			// items.clear();
			if (listAdapter != null) {
				listAdapter.notifyDataSetChanged();
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doGetCount(View view) {

		String cateId = null;
		String identifier = goodsCode.getText().toString();
		Date btime;
		Date etime;
		try {
			btime = simpleDateFormat.parse(fromDate.getText().toString());
			etime = simpleDateFormat2.parse(toDate.getText().toString()
					+ " 23:59:59");

			total = selloutDao.getCount(cateId, identifier, btime.getTime(),
					etime.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.i("count============", total + "");
	}

	@Override
	protected void onDataReceived(byte[] buffer, int size) {
		// TODO Auto-generated method stub

	}
}
